/**
 ----------------------
 1.整张表的增删改查
 2.逻辑复用
 ----------------------
 */
import { useUploadFile } from '@/utils/file/file';
import { treeFormConfig } from './form';
import { treeTable } from './table';
import {
  deleteTree,
  fetchTreeById,
  fetchTreeList,
  exportTree,
  importTree,
} from '@/api/modules/ax/tree/tree';
import { response } from '@/utils/table/table';
import { setContextMenu } from '@/views/components/contextmenu/data';
import type { AxTree } from '@/api/modules/ax/tree/types';
/**
 * @description: 根据条件获取列表数据
 */
export const treeList = async () => {
  try {
    treeTable.value.loading = true;
    const { data } = await fetchTreeList(treeTable.value.query);
    treeTable.value.data = coverTree(data.rows)
    console.log(treeTable.value.data);

    treeTable.value.query.total = data.total;
    treeTable.value.loading = false;
  } catch (error) {
    treeTable.value.loading = false;
  }
};

/**
 * @description: 根据ID查询数据,并打开表单页面
 * @param {number} id
 */
export const treeEdit = async (id?: number) => {
  let targetId: number | string = id ? id : treeTable.value.keys[0];
  treeTable.value.loading = true;
  const { data } = await fetchTreeById(targetId);
  if (data.data) {
    treeFormConfig.value.form = data.data;
    treeFormConfig.value.display = true;
  }
  treeTable.value.loading = false;
};

/**
 * @description:
 * 清空表单所有内容
 * 打开表单页面
 */
export const treeCreate = async () => {
  treeFormConfig.value.display = true;
  treeFormConfig.value.reset();
};

export const treeDelete = async (id?: number) => {
  let ids = id ? [id] : treeTable.value.keys;
  await response(deleteTree, ids);
  await treeList();
  treeTable.value.keys = [];
};

// 导出EXCEL文件
export const treeExport = () => {
  return exportTree(treeTable.value.query);
};

/**
 * @description:搜索
 * 需要将页码设为第一页，避免翻页后搜不到内容
 */
export const treeSearch = () => {
  treeTable.value.query.pageNum = 1;
  treeList();
};

/**
 * @description: 使用excel导入文件
 */
export const treeImport = async () => {
  const files = await useUploadFile({
    accept: '.xls, .xlsx',
  });
  importTree(files[0]);
};

/**
 * @description:
 *  显示右键菜单
 *  在表格和卡片中复用
 * @param {AxTree} item
 */
export const displayTreeMenu = (item: AxTree) => {
  treeFormConfig.value.form = item;
  treeTable.value.keys = [item.id];
  setContextMenu({
    items: treeTable.value.contextmenu,
  });
};
export const coverTree = (data: AxTree[]): any[] => {
  const buildTree = (data: AxTree[]): AxTree[] => {
    const nodeMap = new Map<number, any>();

    // 初始化映射
    data.forEach(node => {
      nodeMap.set(node.id, {
        val: node.val,
        title: node.title,
        label: node.label,
        children: [],
        id: node.id,
      });
    });

    // 构建树结构
    const tree: AxTree[] = [];

    data.forEach(node => {
      const treeNode = nodeMap.get(node.id)!;
      if (node.parentId === 0 || !nodeMap.has(node.parentId!)) {
        // 根节点
        tree.push(treeNode);
      } else {
        // 子节点
        const parentTreeNode = nodeMap.get(node.parentId!)!;
        parentTreeNode.children!.push(treeNode);
      }
    });

    return tree;
  };
  return buildTree(data);
};
